package ip

import (
	"fmt"
	"net"

	"gitee.com/liumou_site/gns/eth"
)

// GetDefaultNetworkSubnet 获取本机默认网卡的网段信息
func GetDefaultNetworkSubnet() ([]net.IP, error) {
	iface, err := eth.NewEth(false).GetDefaultInterface()
	if err != nil {
		return nil, err
	}
	addrs, err := iface.Addrs()
	if err != nil {
		return nil, err
	}
	for _, addr := range addrs {
		if ipnet, ok := addr.(*net.IPNet); ok && ipnet.IP.To4() != nil {
			return CIDRToIPRange(ipnet.String())
		}
	}
	return nil, fmt.Errorf("未找到默认网卡的IPv4地址")
}

// PrintDefaultNetworkSubnet 打印本机默认网卡网段内的所有IP地址
func PrintDefaultNetworkSubnet() error {
	ips, err := GetDefaultNetworkSubnet()
	if err != nil {
		return err
	}
	for i, ip := range ips {
		fmt.Printf("IP #%d: %s\n", i+1, ip.String())
	}
	return nil
}
